package com.wy.business.market.apps.services;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.axis.utils.tcpmon;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Function;
import com.wy.framework.constants.Constants;
import com.wy.framework.constants.DBConstant;
import com.wy.framework.constants.FieldConstant;
import com.wy.framework.constants.RtnCodeConstant;
import com.wy.framework.dao.ErrorSqlException;
import com.wy.framework.exceptions.ServiceException;
import com.wy.framework.pojos.TSysFunction;
import com.wy.framework.pojos.TSysFunctionVersion;
import com.wy.framework.pojos.TSysOrginfo;
import com.wy.framework.pojos.TSysUserinfo;
import com.wy.framework.pojos.TSysUserselectedfunction;
import com.wy.framework.services.AbstractBaseService;
import com.wy.framework.services.login.LoginService;
import com.wy.component.dataConvert.BeanUtil;
import com.wy.component.image.ImageUtil;
import com.wy.component.properties.PropertiesUtil;

/**
 * 项目名称：openportal 类名称：AppManageService 类描述：我的APP仓库_APP管理 创建人：张旭星 创建时间：2016-3-21
 * 上午11:47:28 修改人：张旭星 修改时间：2016-3-21 上午11:47:28 版本信息：@version 1.0 Copyright (c)
 * 2016万雍科技（上海）有限公司-版权所有 修改备注：
 * 
 * @version
 */
/**
 * 项目名称：openportal
 * 类名称：AppManageService
 * 类描述：
 * 创建人：朱仕稳
 * 创建时间：2016-3-28 下午4:05:30
 * 修改人  朱仕稳
 * 修改时间：2016-3-28 下午4:05:30
 * 版本信息：@version 1.0
 * Copyright (c) 2016万雍科技（上海）有限公司-版权所有  
 * 修改备注：
 * @version 
 */
/**
 * 项目名称：openportal
 * 类名称：AppManageService
 * 类描述：
 * 创建人：朱仕稳
 * 创建时间：2016-3-28 下午4:05:31
 * 修改人  朱仕稳
 * 修改时间：2016-3-28 下午4:05:31
 * 版本信息：@version 1.0
 * Copyright (c) 2016万雍科技（上海）有限公司-版权所有  
 * 修改备注：
 * @version 
 */
@Service
public class AppManageService extends AbstractBaseService {

	private static final char[] object = null;
	private static Logger logger = LoggerFactory
			.getLogger(AppManageService.class);

	public List list() throws ErrorSqlException {
		return dataBaseDao.queryForList("t_sys_function.listAppManage",
				new ArrayList());
	}


	@SuppressWarnings("unchecked")
	public List<Map> myListChecked(String tab) throws ErrorSqlException {
		List params = new ArrayList();
		params.add(loginUser().getUserId());

		String stateSql = "";
		//所有
		if(StringUtils.equals(tab, "tab1_1"))
			stateSql="";
		// 待审核
		else if (StringUtils.equals(tab, "tab1_2"))
			stateSql = " AND F.STATE in ('0','2','4') ";
		// 通过
		else if (StringUtils.equals(tab, "tab1_3"))
			stateSql = " AND F.STATE in ('6') ";
		// 驳回 或 已下架
		else if (StringUtils.equals(tab, "tab1_4"))
			stateSql = " AND (F.STATE in ('1','3','5') OR F.STATE in ('6') AND F.UPDOWNSTATE='0') ";
		return dataBaseDao.queryForList("t_sys_function.listAppManageInMyStayCheck", params, stateSql + " ORDER BY F.SUBMITTIME DESC ");
	}
	
	@SuppressWarnings("unchecked")
	public List<Map> myListCheck() throws ErrorSqlException {
		List params = new ArrayList();
		params.add(loginUser().getUserId());
		return dataBaseDao.queryForList("t_sys_function.listAppManagStayCheck",params);
	}
	@SuppressWarnings("unchecked")
	public List<Map> myListAudited(String source) throws ErrorSqlException {
		String sql = "";
		if(StringUtils.equals(source, "developer"))
			sql = "  and t.userid='"+loginUser().getUserId()+"' ";
		return dataBaseDao.queryForList("t_sys_function.listAppManagStayAudit",null,sql);
	}
	@SuppressWarnings("unchecked")
	public List<Map> myListToDo() throws ErrorSqlException {
		return dataBaseDao.queryForList("t_sys_function.listAppManagToDo");
	}
	@SuppressWarnings("unchecked")
	public List<Map> myListMarketNews() throws ErrorSqlException {
		
		return dataBaseDao.queryForList("t_market_news.listMarketNews");
	}
	@SuppressWarnings("unchecked")
	public List<Map> myListLoginLink() throws ErrorSqlException {
		
		return dataBaseDao.queryForList("t_sys_function.listAppManagLoginLink");
	}
	/**
	 * Function Name               queryAppVersion                                   
	 * @return          		             
	 * @throws ErrorSqlException 
	 * @description TODO(根据应用编号查询应用版本信息)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-25 下午6:34:23           朱仕稳                    Initial
	 **********************************************************************
	 */
	@SuppressWarnings("unchecked")
	public List<Map> queryAppVersion(String functionId,String versionId) throws ErrorSqlException {
		List param=new ArrayList();
		param.add(functionId);
		param.add(versionId);
		return this.dataBaseDao.queryForList("t_sys_function_version.queryAppVersion", param);
	}

	
	/**
	 * Function Name               queryAppScreenshot                                   
	 * @return          		             
	 * @throws ErrorSqlException 
	 * @description TODO(根据应用Id查询应用截图)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-25 下午11:14:29           朱仕稳                    Initial
	 **********************************************************************
	 */
	@SuppressWarnings("unchecked")
	public List<Map> queryAppScreenshot(String functionId) throws ErrorSqlException {
		return this.dataBaseDao.queryForList("t_market_screenshots.queryAppScreenshotById",functionId);
	}

	
	
	/**
	 * Function Name               queryAppVersionNoList                                   
	 * @param functionId
	 * @return          		             
	 * @throws ErrorSqlException 
	 * @description TODO(根据应用ID查询版本编号)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-28 下午1:58:12          朱仕稳                     Initial
	 **********************************************************************
	 */
	 
	@SuppressWarnings("unchecked")
	public List<Map> queryAppVersionNoList(String functionId) throws ErrorSqlException {
		return this.dataBaseDao.queryForList("t_sys_function_version.queryAppVersionNoList",functionId);
	}

	
	
	/**
	 * Function Name               updateAppVersion                                   
	 * @param functionId
	 * @param versionId
	 * @return          		             
	 * @throws ErrorSqlException 
	 * @throws IOException 
	 * @description TODO(回退版本)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-28 下午2:35:26          朱仕稳                     Initial
	 **********************************************************************
	 */
	 
	public void updateAppVersion(String functionId, String versionId) throws ErrorSqlException, IOException {
		
		//修改回退版本数据是否有效
		TSysFunctionVersion tfv=(TSysFunctionVersion) this.dataBaseDao.load(TSysFunctionVersion.class, versionId);
		tfv.setIsavailable("1");
		tfv.setUpdateTime(new Date(System.currentTimeMillis()));
		this.dataBaseDao.update(tfv);
		//回退成功要删除版本表数据
		String hql="delete from TSysFunctionVersion tfv where tfv.versionno>=? and tfv.functionid=?";
		this.dataBaseDao.getHibernateTemplate().bulkUpdate(hql, tfv.getVersionno(),tfv.getFunctionid());
		
		//更新应用的当前版本的信息
		TSysFunction tf=(TSysFunction) this.dataBaseDao.load(TSysFunction.class, functionId);
		tf.setVersionNo(tfv.getVersionno());//版本编号
		tf.setDescription(tfv.getDescription());//版本描述
		tf.setFunctionName(tfv.getFunctionname());//应用名称
		tf.setIconName(tfv.getIconname());//图标
		tf.setActionUrl(tfv.getActionurl());//html功能URL/应用入口
		tf.setAppSize(tfv.getAppsize());//应用大小
		tf.setAppZipUrl(tfv.getAppzipurl());//应用zip包地址
		tf.setVersionName(tfv.getVersionname());//应用版本名称
		tf.setVersionNo(tfv.getVersionno());//应用版本号
		tf.setDeploymentType(tfv.getDeploymenttype());//部署类型
		tf.setManageUrl(tfv.getManageurl());//应用后台入口
		tf.setUpgradeContent(tfv.getUpgradecontent());//升级内容
		tf.setUpdateTime(new Timestamp(System.currentTimeMillis()));
		tf.setState("6");//回退成功，强行置状态为验收通过，6：表示验收通过
		tf.setUpDownState("1");//回退成功，即修改状态为已上架，1：表示已上架
		this.dataBaseDao.update(tf);
		
		//versionId.zip,覆盖到functionId.zip,如果没有,则跳
		String oldZipPath = this.getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes", "")  + "upload/zip/" + tfv.getVersionid() + ".zip";
		if(new File(oldZipPath).exists()){
			String newZipPath = this.getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes", "")  + "upload/zip/" + tf.getFunctionId() + ".zip";
			FileUtils.copyFile(new File(oldZipPath), new File(newZipPath));
		}
	}

	
	
	/**
	 * Function Name               updateAppUpDownState                                   
	 * @param functionId          		             
	 * @throws ErrorSqlException 
	 * @description TODO(修改应用的上下架状态)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-28 下午4:05:33          朱仕稳                     Initial
	 **********************************************************************
	 */
	 
	public void updateAppUpDownState(String functionId,String state,String reason) throws ErrorSqlException {
		TSysFunction tsf=(TSysFunction) this.dataBaseDao.load(TSysFunction.class, functionId);
		//0:已下架,1:已上架
		tsf.setUpDownState(state);
		if (StringUtils.equals(state, "0")) {
			tsf.setAcceptanceResult(reason);
		}else{
			tsf.setAcceptanceResult("");
		}
	}
	/*
	 * 查询所有的App应用分类
	 * */
	@SuppressWarnings("unchecked")
	public List<Map> queryAppList() throws ErrorSqlException {
		return this.dataBaseDao.queryForList("T_SYS_CATEGORY_LIST.queryApp");
	}
	/*
	 * 根据id查询对应的App
	 * */
	@SuppressWarnings("unchecked")
	public List<Map> queryAllApp(String  categoryid) throws ErrorSqlException {
		
		return this.dataBaseDao.queryForList("T_SYS_CATEGORY_LIST.queryAllApp",categoryid);
			}
	@SuppressWarnings("unchecked")
	public List<Map> initAllApp() throws ErrorSqlException {
		
		return this.dataBaseDao.queryForList("T_SYS_CATEGORY_LIST.initAllApp");
			}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String queryPreVersionId(String functionId) throws ErrorSqlException{
		List<Map> list=dataBaseDao.queryForList("T_SYS_FUNCTIONVERSION.QUERYPREVERSION", functionId);
		if (list !=null && list.size()>0) {
			return (String) list.get(0).get("versionId");
		}
		return null;
	}
	
	public void deleteApp(String functionId) throws ErrorSqlException{
		dataBaseDao.delete(TSysFunction.class,functionId);
	}
}
